package org.cdivtc.exam.service.impl;

import org.cdivtc.exam.DTO.StudentAddDTO;
import org.cdivtc.exam.entity.Students;
import org.cdivtc.exam.mapper.StudentsMapper;
import org.cdivtc.exam.service.BusinessException;
import org.cdivtc.exam.service.StudentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map; // 推荐使用接口类型声明变量

/**
 * <p>
 * 学生基本信息表 服务实现类
 * </p>
 *
 * @author xiaogoudashuai
 * @since 2025-03-27
 */
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements StudentsService {
    @Autowired
    StudentsMapper studentsMapper;
    @Autowired
    PasswordEncoder passwordEncoder;


    public StudentsServiceImpl(StudentsMapper studentsMapper) {
        this.studentsMapper = studentsMapper;
    }

    @Override
    public Map<String, Object> login(String account, String password) {
        Map<String, Object> result = new HashMap<>();
// 1. 根据账号查询学生
        Students student = studentsMapper.selectByAccount(account);
        if (student == null) {
            result.put("success", false);
            result.put("message", "账号不存在");
            return result;
        }

        // 2. 验证密码（简化版，实际项目应加密比对）
        if (!password.equals(student.getPassword())) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }
        // 3. 登录成功，返回学生基本信息
        result.put("success", true);
        result.put("data", student);
        return result;
    }

    @Override
    @Transactional
    public void updatePhoneAndPassword(Long studentId, String newPhone, String newPassword) {
// 1. 验证手机号
        if (!newPhone.matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        // 2. 验证密码
        if (newPassword.length() < 6 || newPassword.length() > 20) {
            throw new IllegalArgumentException("密码长度需在6-20位之间");
        }

        // 3. 检查手机号是否已被使用
        if (studentsMapper.existsByPhoneAndNotStudent(newPhone, studentId)) {
            throw new IllegalStateException("该手机号已被其他学生使用");
        }

        // 4. 加密密码
        String encodedPassword = passwordEncoder.encode(newPassword);

        // 5. 执行更新
        int affectedRows = studentsMapper.updatePhoneAndPassword(studentId, newPhone, encodedPassword);
        if (affectedRows == 0) {
            throw new RuntimeException("学生不存在或更新失败");
        }
    }

    @Override
    public Students addStudent(StudentAddDTO studentDTO) {
        // 1. 验证账号唯一性
        if (studentsMapper.existsByAccount(studentDTO.getAccount())) {
            throw new BusinessException("账号已存在");
        }

        // 2. 密码加密
        String encodedPassword = passwordEncoder.encode(studentDTO.getPassword());

        // 3. 转换DTO为Entity
        Students student = new Students();
        student.setName(studentDTO.getName());
        student.setGender(studentDTO.getGender());
        student.setAccount(studentDTO.getAccount());
        student.setPassword(studentDTO.getPassword());
        student.setPhone(studentDTO.getPhone());
        student.setCreateTime(LocalDateTime.now());
        student.setCertificationStatus("未获取");

        // 4. 插入数据库
        int affectedRows = studentsMapper.insert(student);
        if (affectedRows == 0) {
            throw new BusinessException("新增学生失败");
        }

        return student;
    }


}
